<template>
  <div class="page">
    <LsdDialog :dialogConfig="dialogConfig" @handleBtn="handleBtn" @close="handleClose">
      <LsdDialogTitle slot="dialog" :titleConfig="titleConfig" :activeNames="activeNames">
        <DialogForm ref="formComponent" slot="slot1" :formConfig="formConfig" />
        <DialogForm ref="formComponent1" slot="slot2" :formConfig="formConfig1" />
        <el-form slot="slot2" ref="form" :model="upload_form" label-width="140px" size="small" class="upload">
          <el-form-item label="附件：">
            <el-upload class="upload-demo" action="" :on-preview="handlePreview" :before-upload="handleBeforeUpload"
              :on-remove="handleRemove" :limit="99" :file-list="upload_form.fileList" ref="upload"
              accept="image/jpeg,image/png,application/pdf,application/msword">
              <el-button size="mini" style="color: #3270ff">上传</el-button>
              <div slot="tip" class="el-upload__tip">
                <!-- 支持jpg/png/pdf/doc等文件，且不超过50mb -->
                支持jpg、png大小不超过3M，建议尺寸350*600
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <DialogForm ref="formComponent2" slot="slot3" :formConfig="formConfig2" />
      </LsdDialogTitle>
    </LsdDialog>
  </div>
</template>

<script>
import {
  khfwFeedbackSave,
  // getdepartmentlist,
  // getpersonlist,
  // getemergencyResponselist,
  // gettaskTypelist,
  getinfo,
  editlist,
  khfwFeedbacksubmit
} from "@/api/EmergencyDisposal/khfw";
import {
  getpublishedinfo
} from "@/api/EmergencyDisposal/xymld.js";
import { showTime } from "@/lib";
import { GetUsers, UploadFile, loadFile, getOrggetSameLevel, getSuperiorUntilId } from "@/api/common.js";
export default {
  name: "Add",
  components: {},
  props: {
    dialogvisible: {
      type: Boolean,
      default: false
    },
    type: {
      type: Object,
      default: function () {
        return {};
      }
    },
    id: {
      type: [String, Number],
      default: function () {
        return "";
      }
    }
  },
  data() {
    return {
      // 弹窗表单信息
      formConfig2: {
        formData: [
          {
            type: "input",
            label: "填报人",
            prop: "creator",
            class: "third",
            lableWidth: "180px",
            isDisabled: true
          },
          {
            type: "input",
            label: "单位及部门",
            prop: "creatorUnit",
            // class: "third",
            lableWidth: "100px",
            isDisabled: true
          },
          {
            type: "input",
            label: "填报时间",
            prop: "createTime",
            class: "third",
            lableWidth: "120px",
            isDisabled: true
          }
        ],
        rules: {
          sourceInfoId: [
            { required: true, message: "请选择响应命令单", trigger: "change" }
          ]
        }
      },
      // 弹窗表单信息
      formConfig1: {
        formData: [
          {
            type: "input",
            label: "工单名称",
            prop: "orderName",
            class: "half",
            lableWidth: "140px"
          },
          {
            type: "select",
            label: "工单类型",
            prop: "taskType",
            dic: "dic_gdlx",
            class: "half",
            lableWidth: "140px",
            isShow: true,
            option: [
              {
                label: "95598抢修工单",
                value: "1"
              }
            ]
          },
          {
            type: "selectTree",
            label: "派发单位/部门",
            prop: "distributingUnit",
            name: "distributingUnitId",
            title: "派发单位/部门选择",
            KeyWord: "KeyWord1",
            treeRef: "treeRef1",
            isDisabled: true,
            multiple: false,
            commonClick: true,
            isSplice: true,
            chooseUnit: true,
            clickClose: true,
            choose: false,
            ref: "xiangying_select",
            class: "half",
            lableWidth: "140px",
            option: [],
            treeData: {
              data: [],
              default: ["1"],
              checked: [],
              props: {
                children: "children",
                label: "orgName",
                value: "id"
              }
            }
          },
          {
            type: "dataPicker",
            label: "要求完成时间",
            prop: "planFinishTime",
            class: "half",
            dateType: "datetime",
            lableWidth: "140px"
          },
          {
            type: "selectTree",
            label: "责任单位/部门",
            prop: "dutyUnit",
            name: "dutyUnitId",
            title: "责任单位/部门选择",
            KeyWord: "KeyWord2",
            treeRef: "treeRef2",
            multiple: false,
            commonClick: true,
            isSplice: true,
            chooseUnit: true,
            clickClose: true,
            choose: false,
            ref: "zeren_select",
            class: "half",
            lableWidth: "140px",
            option: [],
            treeData: {
              data: [],
              default: ["1"],
              checked: [],
              props: {
                children: "children",
                label: "orgName",
                value: "id"
              }
            }
          },
          {
            type: "select",
            label: "责任人",
            prop: "dutyOfficerId",
            dic: "dic_zrr",
            class: "half",
            lableWidth: "140px",
            isShow: true,
            option: [],
            filterable: true
          },
          {
            type: "select",
            label: "用户类型",
            prop: "userType",
            class: "half",
            lableWidth: "140px",
            option: [
              {
                label: "重要用户",
                value: "重要用户"
              },
              {
                label: "非重要用户",
                value: "非重要用户"
              }
            ]
          },
          {
            type: "input",
            label: "故障地址",
            prop: "breakdownAddress",
            class: "half",
            lableWidth: "140px"
          },
          {
            type: "textarea",
            label: "任务内容",
            prop: "orderContent",
            class: "sjgy",
            lableWidth: "140px"
          }
          // {
          //   type: "upload",
          //   label: "附件",
          //   prop: "ztqks",
          //   action: "#",
          //   limit: 99,
          //   httpRequest: () => { },
          //   lableWidth: "140px",
          //   isDisabled: true
          // }
        ],
        rules: {
          orderName: [
            { required: true, message: "请输入工单名称", trigger: "blur" }
          ],
          taskType: [
            { required: true, message: "请选择工单类型", trigger: "change" }
          ],
          distributingUnit: [
            { required: true, message: "请输入派发单位/部门", trigger: "blur" }
          ],
          planFinishTime: [
            { required: true, message: "请选择要求完成时间", trigger: "change" }
          ],
          dutyUnit: [
            { required: true, message: "请选择责任单位/部门", trigger: "blur" }
          ],
          userType: [
            { required: true, message: "请选择用户类型", trigger: "change" }
          ],
          breakdownAddress: [
            { required: true, message: "请输入故障地址", trigger: "blur" }
          ],
          orderContent: [
            { required: true, message: "请输入任务内容", trigger: "blur" }
          ]
        }
      },
      // 弹窗表单信息
      formConfig: {
        formData: [
          {
            type: "select",
            label: "响应命令单",
            prop: "sourceInfoId",
            name: "sourceInfo",
            dic: "dic_xymld",
            class: "sjgy",
            lableWidth: "140px",
            isShow: true,
            option: [
            ]
          }
        ],
        rules: {
          sourceInfoId: [
            { required: true, message: "请选择响应命令单", trigger: "change" }
          ]
        }
      },
      // 折叠面板信息
      titleConfig: [
        {
          title: "信息来源",
          name: "1",
          slot: "slot1"
        },
        {
          title: "任务信息",
          name: "2",
          slot: "slot2"
        },
        {
          title: "填报信息",
          name: "3",
          slot: "slot3"
        }
      ],
      // 弹窗信息
      dialogConfig: {
        title: "客户抢修工单",
        isShow: false, // 弹窗显示隐藏
        btnList: [
          {
            name: "提交",
            id: "Submit", // 事件名
            type: "primary",
            size: "small"
          },
          {
            name: "保存",
            id: "save",
            size: "small"
          },
          {
            name: "取消",
            id: "cancel",
            size: "small"
          }
        ]
      },
      xymldlist: [],
      activeNames: ["1", "2", "3"],
      zrrlist: [],
      zrdwbmlist: [],
      rwlxlist: [],
      upload_form: {
        fileList: []
      }
    };
  },
  watch: {
    dialogvisible: {
      handler(val) {
        if (val) {
          if (this.type.code === "edit") {
            this.getinfo();
          } else {
            this.$nextTick(() => {
              this.$set(this.$refs.formComponent1.form, "distributingUnit", sessionStorage.getItem("dwbmName"));
              this.$set(this.$refs.formComponent1.form, "distributingUnitId", JSON.parse(sessionStorage.getItem("org")).orgId);
              this.$set(this.$refs.formComponent2.form, "creator", this.getCreator.name);
              this.$set(this.$refs.formComponent2.form, "creatorUnit", sessionStorage.getItem("dwbmName"));
              // this.$set(this.$refs.formComponent2.form, "createTime", new Date().toLocaleString().replace(/\//g, "-"))
              this.$set(this.$refs.formComponent2.form, "createTime", showTime(new Date()));
            });
          }
          this.dialogConfig.isShow = true;
        } else {
          if (this.dialogConfig.isShow) {
            this.dialogConfig.isShow = false;
            this.$emit("list");
            this.cancel();
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    getCreator() {
      const account = sessionStorage.getItem("account");
      const org = sessionStorage.getItem("org");
      const creator = {
        name: (account && JSON.parse(account).realName) || "",
        dept: (org && JSON.parse(org).orgName) || "",
        unitName: (org && JSON.parse(org).unitName) || ""
      };
      return creator;
    }
  },
  created() {
    this.getPublishedResponse();
    this.getAlllist();
  },
  methods: {
    handleClose() {
      this.cancel();
    },
    handleBtn(item) {
      this[item.id]();
    },
    async getinfo() {
      const res = await getinfo({ id: this.id });
      this.$set(this.$refs.formComponent, "form", res);
      this.$set(this.$refs.formComponent1, "form", res);
      this.$set(this.$refs.formComponent2, "form", res);
      console.log(this.$refs.formComponent1);
      this.upload_form.fileList = (res.attachInfo && res.attachInfo.map(item => {
        return {
          name: item.attachName,
          url: item.attachId,
          ...item
        };
      })) || [];
    },
    getAlllist() {
      this.getzrrlist();
      // this.getbmlist()
      // this.getxymldlist()
      // this.getrwlxlist()
      this.GetOrgTreeData();
    },
    // async getbmlist() {
    //   const res = await getdepartmentlist()
    //   this.zrdwbmlist = res
    // },
    // 责任人下拉
    async getzrrlist() {
      // const res = await getpersonlist()
      const res = await GetUsers();
      this.formConfig1.formData[5].option = res.map(item => {
        return {
          label: item.realName,
          value: item.realName
        };
      });
      this.zrrlist = res;
    },
    // 获取责任单位
    async GetOrgTreeData() {
      // const res = await getpersonlist()
      // this.formConfig1.formData[4].option = res;
      // this.formConfig1.formData[2].option = res;// 派发单位部门
      const nowOrgId = JSON.parse(sessionStorage.getItem("org")).orgId;
      const { id } = await getSuperiorUntilId(nowOrgId);
      if (id) {
        getOrggetSameLevel({ orgId: id }).then(res => {
          this.formConfig1.formData[4].treeData.data = res;
        });
      }
    },

    handleNodeClick(data, node, item) {
      console.log(data);
      if (item.label === "派发单位/部门") {
        if (!data.children) {
          let parentName = "";
          if (["直属单位"].includes(node.parent.data.orgName)) {
            parentName = "";
          } else if (["公司本部"].includes(node.parent.data.orgName)) {
            parentName = node.parent.parent.data.orgName;
          } else if (["地市公司"].includes(node.parent.data.orgName)) {
            parentName = "";
          } else {
            parentName = node.parent.data.orgName;
          }
          this.$set(this.$refs.formComponent1.form, "distributingUnit", `${parentName}${data.orgName}`);
          this.$set(this.$refs.formComponent1.form, "distributingUnitId", data.id);
        }
      }
      if (item.label === "责任单位/部门") {
        if (!data.children) {
          let parentName = "";
          if (["直属单位"].includes(node.parent.data.orgName)) {
            parentName = "";
          } else if (["公司本部"].includes(node.parent.data.orgName)) {
            parentName = node.parent.parent.data.orgName;
          } else if (["地市公司"].includes(node.parent.data.orgName)) {
            parentName = "";
          } else {
            parentName = node.parent.data.orgName;
          }
          this.$set(this.$refs.formComponent1.form, "dutyUnit", `${parentName}${data.orgName}`);
          this.$set(this.$refs.formComponent1.form, "dutyUnitId", data.id);
        }
      }
    },
    // async getxymldlist() {
    //   const res = await getemergencyResponselist()
    //   this.xymldlist = res
    // },
    // async getrwlxlist() {
    //   const dictGroup = "dic_gzgd"
    //   const res = await gettaskTypelist({ dictGroup })
    //   this.rwlxlist = res
    // },
    // 保存
    async save() {
      this.$refs.formComponent.isValidate();
      this.$refs.formComponent1.isValidate();
      const flag = this.$refs.formComponent.flag;
      const flag1 = this.$refs.formComponent1.flag;
      const sourceInfo = this.formConfig.formData[0].option.find(item => item.value == this.$refs.formComponent.form.sourceInfoId).label;
      // const dutyUnit = this.formConfig1.formData[4].option.find(item => item.value == this.$refs.formComponent1.form.dutyUnitId).label
      // const dutyOfficer = this.formConfig1.formData[5].option.find(item => item.value == this.$refs.formComponent1.form.dutyOfficerId).label
      const params = {
        breakdownAddress: this.$refs.formComponent1.form.breakdownAddress,
        distributingUnit: this.$refs.formComponent1.form.distributingUnit,
        distributingUnitId: this.$refs.formComponent1.form.distributingUnitId,
        dutyUnit: this.$refs.formComponent1.form.dutyUnit,
        dutyUnitId: this.$refs.formComponent1.form.dutyUnitId,
        orderContent: this.$refs.formComponent1.form.orderContent,
        planFinishTime: this.$refs.formComponent1.form.planFinishTime,
        taskType: this.$refs.formComponent1.form.taskType,
        dutyOfficerId: this.$refs.formComponent1.form.dutyOfficerId,
        sourceInfoId: this.$refs.formComponent.form.sourceInfoId,
        userType: this.$refs.formComponent1.form.userType,
        // dutyUnit: dutyUnit,
        orderName: this.$refs.formComponent1.form.orderName,
        sourceInfo: sourceInfo,
        // dutyOfficer: dutyOfficer,
        dutyOfficer: this.$refs.formComponent1.form.dutyOfficerId,
        attachInfo: this.upload_form.fileList
      };
      if (flag && flag1) {
        if (this.type.code === "add") {
          params.creator = this.$refs.formComponent2.form.creator;
          params.creatorUnit = this.$refs.formComponent2.form.creatorUnit;
          params.createTime = showTime(new Date());

          await khfwFeedbackSave(params);
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.$emit("update:dialogvisible", false);
        } else if (this.type.code === "edit") {
          params.id = this.id;
          await editlist(params);
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.$emit("update:dialogvisible", false);
        }
      }
    },
    // 提交
    async Submit() {
      this.$refs.formComponent.isValidate();
      this.$refs.formComponent1.isValidate();
      const flag = this.$refs.formComponent.flag;
      const flag1 = this.$refs.formComponent1.flag;
      const sourceInfo = this.formConfig.formData[0].option.find(item => item.value == this.$refs.formComponent.form.sourceInfoId).label;
      // const dutyUnit = this.formConfig1.formData[4].option.find(item => item.value == this.$refs.formComponent1.form.dutyUnitId).label
      // const dutyOfficer = this.formConfig1.formData[5].option.find(item => item.value == this.$refs.formComponent1.form.dutyOfficerId).label
      const params = {
        breakdownAddress: this.$refs.formComponent1.form.breakdownAddress,
        distributingUnit: this.$refs.formComponent1.form.distributingUnit,
        distributingUnitId: this.$refs.formComponent1.form.distributingUnitId,
        dutyUnit: this.$refs.formComponent1.form.dutyUnit,
        dutyUnitId: this.$refs.formComponent1.form.dutyUnitId,
        orderContent: this.$refs.formComponent1.form.orderContent,
        planFinishTime: this.$refs.formComponent1.form.planFinishTime,
        taskType: this.$refs.formComponent1.form.taskType,
        dutyOfficerId: this.$refs.formComponent1.form.dutyOfficerId,
        sourceInfoId: this.$refs.formComponent.form.sourceInfoId,
        userType: this.$refs.formComponent1.form.userType,
        // dutyUnit: dutyUnit,
        // dutyUnit: this.$refs.formComponent1.form.dutyUnitId,
        orderName: this.$refs.formComponent1.form.orderName,
        sourceInfo: sourceInfo,
        // dutyOfficer: dutyOfficer,
        dutyOfficer: this.$refs.formComponent1.form.dutyOfficerId,
        attachInfo: this.upload_form.fileList
      };
      if (flag && flag1) {
        if (this.type.code === "add") {
          params.creator = this.$refs.formComponent2.form.creator;
          params.creatorUnit = this.$refs.formComponent2.form.creatorUnit;
          params.createTime = showTime(new Date());

          await khfwFeedbacksubmit(params);
          this.$message({
            message: "提交成功",
            type: "success"
          });
          this.$emit("update:dialogvisible", false);
        } else if (this.type.code === "edit") {
          params.id = this.id;
          await khfwFeedbacksubmit(params);
          this.$message({
            message: "提交成功",
            type: "success"
          });
          this.$emit("update:dialogvisible", false);
        }
      }
    },
    // 取消
    cancel() {
      this.$refs.formComponent.form = this.$refs.formComponent.$options.data().form;
      this.$refs.formComponent1.form = this.$refs.formComponent1.$options.data().form;
      this.$refs.formComponent2.form = this.$refs.formComponent2.$options.data().form;
      this.upload_form.fileList = [];
      this.$nextTick(() => {
        this.$refs.formComponent.$refs.formInlines.clearValidate();
        this.$refs.formComponent1.$refs.formInlines.clearValidate();
        this.$refs.formComponent2.$refs.formInlines.clearValidate();
      });
      this.$emit("update:dialogvisible", false);
    },
    // 获取已发布的响应命令单
    getPublishedResponse() {
      getpublishedinfo({}).then(res => {
        let options = [];
        options = res.map(item => {
          return {
            label: item.responseName,
            value: item.id,
            ...item
          };
        });
        this.formConfig.formData[0].option = options;
      });
    },
    // 上传附件
    handleBeforeUpload(file) {
      const params = {
        file: file,
        directoryId: 2,
        isNew: false,
        moduleName: "emergency"
      };
      UploadFile(this.common.convertFormData(params)).then(data => {
        this.$nextTick(() => {
          this.$set(this.$refs.formComponent1.form, "id", data.id);
          this.upload_form.fileList.push({ name: data.fileName, url: data.id, attachName: data.fileName, attachId: data.id });
        });
      });
    },
    // 下载
    handlePreview(file) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.6)"
      });
      loadFile({ id: file.attachId }).then(res => {
        const a = document.createElement("a");
        const objectUrl = URL.createObjectURL(res);
        a.setAttribute("href", objectUrl);
        a.setAttribute("download", file.name);
        a.click();
        loading.close();
      }).catch(() => {
        loading.close();
      });
    },
    // 移除附件
    handleRemove(file, fileList) {
      console.log(fileList);
      this.upload_form.fileList = fileList;
    }
  }
};
</script>

<style scoped lang="less">
.upload {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}

.leftLine {
  width: 6px;
  height: 20px;
  background: #236dfe;
  border-radius: 4px;
  margin: auto 8px auto 0;
}

.title {
  border-bottom: 1px solid #ccc;
  padding-bottom: 8px;
}

.card {
  margin-bottom: 20px;
}

.content {
  width: 90%;
  position: relative;
  left: 5%;

  p {
    font-size: 16px;
    margin-top: 12px;
  }

  table tr td {
    border: 1px solid #000;
    font-size: 12px;
    text-align: center;
    padding: 10px;
  }
}

:deep(.el-cascader--small) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-size: 16px !important;
}
</style>
